package com.zhl.media.login.mvp.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.orhanobut.hawk.Hawk;
import com.zhl.media.commonres.base.AppActivity;
import com.zhl.media.commonres.view.LoadingDialog;
import com.zhl.media.commonsdk.core.RouterHub;
import com.zhl.media.commonsdk.data.UserUtil;
import com.zhl.media.commonsdk.entity.Token;
import com.zhl.media.commonsdk.entity.User;
import com.zhl.media.commonsdk.impl.CommonTextWatch;
import com.zhl.media.commonsdk.utils.EmptyUtils;
import com.zhl.media.commonsdk.utils.Utils;
import com.zhl.media.login.R;
import com.zhl.media.login.R2;
import com.zhl.media.login.di.component.DaggerLoginComponent;
import com.zhl.media.login.di.module.LoginModule;
import com.zhl.media.login.mvp.contract.LoginContract;
import com.zhl.media.login.mvp.presenter.LoginPresenter;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

@Route(path = RouterHub.LOGIN_LOGINACTIVITY)
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {

    @BindView(R2.id.edt_username)
    EditText edtUsername;
    @BindView(R2.id.edt_password)
    EditText edtPassword;
    @BindView(R2.id.tv_login)
    TextView tvLogin;
    @BindView(R2.id.img_eye)
    ImageView imgEye;
    private boolean eyeOpen = false;
    LoadingDialog dialog;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        dialog = new LoadingDialog.Builder(this).setCancelable(false).setCancelOutside(false).create();
        listenerEdit();
        String oldAcount = UserUtil.getOldAcount();
        String oldPass = UserUtil.getOldPass();
        if (!EmptyUtils.isEmpty(oldAcount)) {
            edtUsername.setText(oldAcount);
            edtUsername.setSelection(oldAcount.length());
            Drawable drawable = ContextCompat.getDrawable(this,R.drawable.phone_lan);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            edtUsername.setCompoundDrawables(drawable, null, null, null);
        }
        if (!EmptyUtils.isEmpty(oldPass)) {
            edtPassword.setText(oldPass);
            edtPassword.setSelection(oldPass.length());
            Drawable drawable = ContextCompat.getDrawable(this,R.drawable.password_lan);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            edtPassword.setCompoundDrawables(drawable, null, null, null);
        }
        resetLoginButton();
        if(UserUtil.getLoginStatus()){
            doLogin();
        }
    }

    private void listenerEdit() {
        edtUsername.addTextChangedListener(new CommonTextWatch() {
            @Override
            public void afterTextChanged(Editable s) {
                String user = edtUsername.getText().toString().trim();
                Drawable drawable;
                if (EmptyUtils.isEmpty(user)) {
                    drawable = getResources().getDrawable(R.drawable.phone_hui);
                } else {
                    drawable = getResources().getDrawable(R.drawable.phone_lan);
                }
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                edtUsername.setCompoundDrawables(drawable, null, null, null);
                resetLoginButton();
            }
        });

        edtPassword.addTextChangedListener(new CommonTextWatch() {
            @Override
            public void afterTextChanged(Editable s) {
                String user = edtPassword.getText().toString().trim();
                Drawable drawable;
                if (EmptyUtils.isEmpty(user)) {
                    drawable = ContextCompat.getDrawable(LoginActivity.this,R.drawable.password_hui);
                } else {
                    drawable = ContextCompat.getDrawable(LoginActivity.this,R.drawable.password_lan);
                }
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                edtPassword.setCompoundDrawables(drawable, null, null, null);
                resetLoginButton();
            }
        });

        edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        edtPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    doLogin();
                }
                return false;
            }
        });
    }

    @OnClick({R2.id.tv_login, R2.id.img_eye})
    public void onClick(View view) {
        if (view.getId() == R.id.tv_login){
            doLogin();
        }
        if (view.getId() == R.id.img_eye){
            if (eyeOpen) {
                //密码 TYPE_CLASS_TEXT 和 TYPE_TEXT_VARIATION_PASSWORD 必须一起使用
                edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                imgEye.setImageResource(R.drawable.eyeclose);
                eyeOpen = false;
            } else {
                //明文
                edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                imgEye.setImageResource(R.drawable.eyeopen);
                eyeOpen = true;
            }
        }
    }

    private void resetLoginButton() {
        String userName = edtUsername.getText().toString();
        String password = edtPassword.getText().toString();
        if (!EmptyUtils.isEmpty(userName)&&!EmptyUtils.isEmpty(password)) {
            tvLogin.setTextColor(ContextCompat.getColor(this, R.color.public_white));
            tvLogin.setBackgroundResource(R.drawable.shape_00bfff_5);
            tvLogin.setEnabled(true);
        }else {
            tvLogin.setTextColor(ContextCompat.getColor(this, R.color.public_color_999999));
            tvLogin.setBackgroundResource(R.drawable.shape_dddddd_5);
            tvLogin.setEnabled(false);
        }
    }

    private void doLogin() {
        String userName = edtUsername.getText().toString();
        String password = edtPassword.getText().toString();
        if (EmptyUtils.isEmpty(userName)) {
            return;
        }
        if (EmptyUtils.isEmpty(password)) {
            return;
        }
        mPresenter.token(userName,password);
    }

    @Override
    public void showLoading() {
        dialog.show();
    }

    @Override
    public void hideLoading() {
        dialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void token(Token token) {
        UserUtil.setTokenInfo(token);
        mPresenter.userInfo();
    }

    @Override
    public void userInfo(User user) {
        UserUtil.setUser(user);
        UserUtil.setLoginStatus(true);
        Utils.navigation(this, RouterHub.APP_MAINACTIVITY);
        killMyself();
    }
}
